package thread;

import java.util.concurrent.CountDownLatch;

/**
 * Creared with IntelliJ IDEA.
 * Description:CountDownLatch(百米赛跑)
 * User:yxd
 * Date:2022-04-02
 * Time:21:44
 */
public class Demo31 {
    public static void main(String[] args) {
        //构造函数的参数表示这里有几个选手参赛
        CountDownLatch latch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            Thread t  = new Thread(()->{//多个线程调度是随机的
                try {
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + "到达终点");
                    latch.countDown();//表示这个选手到达终点,当这里的个数和构造的参数一致时,才会结束这里的操作

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
            t.start();
        }
        //裁判需要等待所有的选手都通过终点线才会结束这场比赛
        //当这些线程没有执行完的时候,await就会是阻塞状态,所有的线程执行完了,await才会返回
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("比赛结束");
    }
}
